package features.advance.jdk.jvm;

import java.io.*;

/**
 * @author LIN
 * @date 2021-07-19
 */


public class FileHelper {
    private String fileName;
    public FileHelper(){

    }

    public FileHelper(String fileName){
        this.fileName=fileName;

    }

    /*
     * 将person对象保存到文件中
     * params:
     * 	p:person类对象
     */
    public File saveObjToFile(Lock p){
        try {
            File file = new File(fileName);
            //写对象流的对象
            ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));

            oos.writeObject(p);                 //将Person对象p写入到oos中

            oos.close();                        //关闭文件流
            return file;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 从文件中读出对象，并且返回Person对象
     */
    public Lock getObjFromFile(){
        try {
            ObjectInputStream ois=new ObjectInputStream(new FileInputStream(fileName));

            Lock lock=(Lock)ois.readObject();              //读出对象

            return lock;                                       //返回对象
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}
